package cn.cloudmenu.android.activity;

import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.cloudmenu.android.CloudMenuApp;
import cn.cloudmenu.android.CoursesOrderedWebSocket;
import cn.cloudmenu.android.MenuCourseBean;
import cn.cloudmenu.android.MenuCourseOrderedBean;
import cn.cloudmenu.android.MenuCoverBean;
import cn.cloudmenu.android.R;
import cn.cloudmenu.android.UserProfile;


public class CoursesOrdered extends ListActivity {
	private  ArrayList<MenuCourseOrderedBean> orderedCourses = new ArrayList<MenuCourseOrderedBean>();
	private CoursesOrderedWebSocket webSocket;
	private CloudMenuApp cloudMenuApp;
	private EditText tableNO;
	private class EfficientAdapter extends BaseAdapter implements OnClickListener {
		private LayoutInflater mInflater;
		private String menuImagePath;

		public EfficientAdapter(Context context) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
			menuImagePath = context.getResources().getString(R.string.menu_image_path);
		}

		/**
		 * The number of items in the list is determined by the number of
		 * speeches in our array.
		 * 
		 * @see android.widget.ListAdapter#getCount()
		 */
		public int getCount() {
			return orderedCourses.size();
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficent to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 * 
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return orderedCourses.get(position);
		}

		/**
		 * Use the array index as a unique id.
		 * 
		 * @see android.widget.ListAdapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			ViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.courses_ordered_list_item_icon_text, null);
				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.courses_ordered_name);
				holder.icon = (ImageView) convertView.findViewById(R.id.courses_ordered_icon);
				holder.button = (Button) convertView.findViewById(R.id.courses_ordered_delete);
				holder.price = (TextView) convertView.findViewById(R.id.courses_ordered_price);
				System.out.println("CoursesOrdered.java holder.price = "+holder.price);
				convertView.setTag(holder);
				// System.out.println("Courses.java holder.button = "+holder.button);
				holder.button.setTag(orderedCourses.get(position));
				holder.button.setOnClickListener(this);
				holder.icon.setTag(orderedCourses.get(position));
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolder) convertView.getTag();
			}

			// Bind the data efficiently with the holder.
			MenuCourseOrderedBean courseOrdered = orderedCourses.get(position);
			System.out.println("CourseOrdered$EfficientAdapter.getView() courseOrdered = "+courseOrdered);
			System.out.println("CourseOrdered$EfficientAdapter.getView() holder = "+holder);
			System.out.println("CourseOrdered$EfficientAdapter.getView() holder.name = "+holder.name);
			System.out.println("CourseOrdered$EfficientAdapter.getView() courseOrdered.getCourseBean() = "+courseOrdered.getCourseBean());
			holder.name.setText(courseOrdered.getCourseBean().getName());
			holder.price.setText("￥"+courseOrdered.getCourseBean().getPrice());
			// holder.icon.setImageBitmap(mIcon);
			holder.icon.setImageDrawable(fetch(menuImagePath + courseOrdered.getCourseBean().getSmallLandscapeImagePath()));

			return convertView;
		}

		public void onClick(View view) {
			System.out.println("Courses.orderCourse(view) is called! view.getTag() = " + view.getTag());
			System.out.println("Courses.orderCourse(view) is called! view.getParent() = " + view.getParent());
			System.out.println("Courses.orderCourse(view) is called! view.getParent() = " + view.getParent());
			MenuCourseOrderedBean orderedCourse = (MenuCourseOrderedBean)view.getTag();
			CoursesOrdered.this.webSocket.removeCourse(orderedCourse);
			CoursesOrdered.this.orderedCourses.remove(orderedCourse);
		    // listPhonebook.remove(view.getId());
		    notifyDataSetChanged();
		}

		class ViewHolder {
			TextView name;
			ImageView icon;
			Button button;
			TextView price;
		}
	}

	private static Drawable fetch(String urlString) {
		try {
			System.out.println("Courses.fetch() urlString = " + urlString);
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet request = new HttpGet(urlString);
			HttpResponse response = httpClient.execute(request);
			Drawable drawable = Drawable.createFromStream(response.getEntity().getContent(), "src");
			return drawable;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.courses_ordered);
		this.cloudMenuApp = (CloudMenuApp)this.getApplicationContext();
		// 从服务器获取菜单菜品分类信息
		orderedCourses.clear();
		/*
		setListAdapter(new EfficientAdapter(this));
		final ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		System.out.println("Courses.onCreate() .............!!!!!!!!!!!!!!!!!!!!!!");
		// 为ListView设置列表项点击监听器
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				System.out.println("Courses.OnItemClickListener() .............!!!!!!!!!!!!!!!!!!!!!!");
				// MenuCategoryBean category = (MenuCategoryBean)
				// parent.getItemAtPosition(position);
				// Intent intent = new Intent(Courses.this, Courses.class);
				// Courses.this.startActivity(intent);
			}
		});
		*/
		try{
			System.out.println("wwwwwwwwwwwwwwwwwwwwwwww WebSocket 1");
			String websocket_url = this.getResources().getString(R.string.websocket_url);
			WebView webView = new WebView(this);
			//Integer menuId = getIntent().getIntExtra("menuId", -1);
			UserProfile user = ((CloudMenuApp)this.getApplication()).getUser();
			MenuCoverBean menu = ((CloudMenuApp)this.getApplication()).getMenu();
			this.webSocket = new CoursesOrderedWebSocket(webView, URI.create(websocket_url), user, menu, this);
			webSocket.connect();
			System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||CoursesOrdered.onCreate()");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void onStart(){
		System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||CoursesOrdered.onStart()");
		super.onStart();
		while(!webscoketEstablished){
			try{
				Thread.sleep(100);
			}catch(Exception e){}
		}
		this.webSocket.orderedCoursesList();
	}

	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG * 2);
		t1.show();
	}
	
	private boolean webscoketEstablished = false;
	private String message;
	public void setMessage(String message){
		this.message = message;
		webscoketEstablished = true;
		cwjHandler.post(updateHeaderMessage);
	}
	
	public void headerMessage(){
		Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
		animation.setFillAfter(true);
		TextView header = (TextView) this.findViewById(R.id.courses_ordered_header);
		header.setText(message);
		header.startAnimation(animation);		
	}
	
	private void packListView(){
		System.out.println("00000000000000000000000000000000ChooseTable.packListView()");
		setListAdapter(new EfficientAdapter(this));
		final ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		//Button closeButton = (Button)this.findViewById(R.id.courses_ordered_list_close_button);
		//closeButton.bringToFront();
		LinearLayout layout = (LinearLayout)this.findViewById(R.id.courses_ordered_footer);
		layout.bringToFront();
	}
	public void close(View view) {
		this.webSocket.close();
		this.finish();
	}
	public void commitOrder(View view) {
		this.tableNO = new EditText(this);
		this.tableNO.setGravity(Gravity.CENTER);
        FrameLayout fl = new FrameLayout(this); 
        System.out.println("CoursesOrdered.commitOrder() fl = "+fl + "this.tableNO="+this.tableNO);
        fl.addView(this.tableNO, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); //给某屏幕添加组件
        this.tableNO.setText("5"); 
        AlertDialog alerdialog=dialogCreate();
        alerdialog.setView(fl);//dialog接收(设置)该组件
        alerdialog.show();//EditText 就可以显示在对话框中了
	}
	public AlertDialog dialogCreate(){
	     return new AlertDialog.Builder(CoursesOrdered.this)  
	     .setTitle("提交订单前，需要输入桌号：")                
	     .setPositiveButton("ok", new DialogInterface.OnClickListener() {                    
	    	 public void onClick(DialogInterface dialog, int whichButton) {                        
	    	  	/* User clicked OK so do some stuff */
	            System.out.println("commit order ? ok clicked "+CoursesOrdered.this.tableNO.getText());
	            String tableNO = CoursesOrdered.this.tableNO.getText().toString();
	     		String courses = "";
	    		for(MenuCourseOrderedBean courseOrdered : orderedCourses){
	    			courses = courses+ ","+courseOrdered.getCourseBean().getId();
	    		}
	    		if(courses.length()>0){
	    			commit(tableNO, courses.substring(1));
	    		}
	    	 }                
	      })                
	     .setNegativeButton("cacle", new DialogInterface.OnClickListener() {                    
	    	 public void onClick(DialogInterface dialog, int whichButton) {                        
	             System.out.println("commit order ? ok clicked "+CoursesOrdered.this.tableNO.getText());
	    	 }                
	      })                
	     .create();    
	}
	
	private void commit(String tableNO, String courses) {
		String href = getResources().getString(R.string.order_commit_url);
		Integer menuId = getIntent().getIntExtra("menuId", -1);
		href = href + "&menuId="+menuId;
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = tm.getDeviceId();//通过API获取
		href = href + "&deviceId="+deviceId;
		href = href + "&tableNo="+tableNO;
		href = href + "&courses="+courses;
		//if (menuId.equals(-1L) || tagId.equals(-1)) return false;
		href = href + menuId;// + "&tagId=" + tagId;
		System.out.println("CoursesOrdered.commit() courses = "+courses+" href = " + href);
		HttpPost request = new HttpPost(href);
		try {
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据
			String retSrc = EntityUtils.toString(httpResponse.getEntity());

			// 生成 JSON 对象
			JSONObject result = new JSONObject(retSrc);
			if(result.getBoolean("success")){
				displayMessage("点单已经提交成功。");
			}else{
				displayMessage(result.getString("message"));
			}
		} catch (Exception e) {
			displayMessage(e.getMessage());
			e.printStackTrace();
		}
	}
	public void setOrderedCoursesList(String courses) {
		orderedCourses.clear();
		try {
			String[] pairs = courses.split(":");
			for (String pair : pairs) {
				String[] ids = pair.split(",");
				String orderedId = ids[0];
				String courseId = ids[1];
				MenuCourseBean bean = this.cloudMenuApp.getAllCoursesInCurrentMenu().get(Integer.valueOf(courseId));
				orderedCourses.add(new MenuCourseOrderedBean(Integer.parseInt(orderedId), bean));
			}
			cwjHandler.post(mUpdateResults);
		} catch (Exception e) {
			//e.printStackTrace();
			displayMessage(e.getMessage());
		}
	}
	
	final Handler cwjHandler = new Handler();

	final Runnable mUpdateResults = new Runnable() {
		public void run() {
	    	packListView();
	    }
	};
	
	final Runnable updateHeaderMessage = new Runnable() {
		public void run() {
			headerMessage();
	    }
	};

}